package com.thwcompany.service;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @program: springboot-rabbit-mq
 * @author: tenghw
 * @create: 2024-01-27 15:32
 * @Version 1.0
 * @description:
 **/
@Service
public class DelaySendService {
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";// 延迟交换机名称
    public static final String DELAYED_ROUTING_KEY = "delayed.routingKey";// 延迟队列绑定的路由键

    @Autowired
    RabbitTemplate rabbitTemplate;

    public void sendDelayMessage(String message, Integer delayTime) {
        rabbitTemplate.convertAndSend(DELAYED_EXCHANGE_NAME , DELAYED_ROUTING_KEY, message, messagePostProcessor -> {
            MessageProperties properties = messagePostProcessor.getMessageProperties();
            // 在发送消息时设置消息头x-delay来指定延迟时间。这样当消息到达RabbitMQ服务器时，延迟插件会根据这个消息头自动处理消息的延迟投递。
            properties.setHeader("x-delay", delayTime); // 延迟多少秒
            //properties.getMessageProperties().setDelay(delayTime); // 也是设置延迟时间的
            return messagePostProcessor;
        });
    }

}